<template>
    <el-card shadow="never" class="common-card">
        <template #header>
            <el-row justify="space-between" align="middle">
                <h1>产品管理</h1>
                <el-breadcrumb sepatrator="/">
                    <el-breadcrumb-item to="/control">管理首页</el-breadcrumb-item>
                    <el-breadcrumb-item to="/control/product">产品管理</el-breadcrumb-item>
                    <el-breadcrumb-item>产品列表</el-breadcrumb-item>
                </el-breadcrumb>
            </el-row>
        </template>

        <div class="common-search">
            <el-form :inline="true" :module="queryForm" ref="queryFormRef">
                <el-form-item>
                    <el-button @click="delBatchByIds" type="danger" v-if="delIds.length > 0">批量删除</el-button>
                </el-form-item>
                <el-form-item label="选择审核" prop="status">
                    <el-select style="width: 220px;" v-model.number="queryForm.status" placeholder="选择审核" clearable>
                        <el-option :value="1" label="未审核" />
                        <el-option :value="2" label="已审核" />
                    </el-select>

                    <el-form-item label="开始价格" prop="minPrice">
                        <el-input-number v-model.number="queryForm.minPrice" :min="0" clearable
                            controls-position="right" placeholder="开始价" />
                    </el-form-item>
                    <el-form-item label="结束价格" prop="maxPrice">
                        <el-input-number v-model.number="queryForm.maxPrice" :min="0" clearable
                            controls-position="right" placeholder="结束价" />
                    </el-form-item>

                </el-form-item>
                <el-form-item label="输入关键字" prop="keyword">
                    <el-input style="width: 220px;" v-model.trim="queryForm.keyword" placeholder="请输入关键字" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button tpye="primary" @click="getProductList">搜索</el-button>
                    <el-button type="primary" @click="onRefralsh">刷新</el-button>
                </el-form-item>

                <el-form-item>
                    <el-button circle>
                        <el-icon type="warning">
                            <refresh />
                        </el-icon>
                    </el-button>
                </el-form-item>
            </el-form>
            <el-button type="primary" @click="openDialog()">新增</el-button>
        </div>


        <el-table style="width: 100%;" stripe v-loading="loading" :data="tableData" 
        ref="tableRef" border @selection-change="onselectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="缩图" width="120" #default="scope">
                <el-popover placement="top" :width="300" trigger="hover">
                    <el-image style="width: 100%;" fit="cover" :src="$resolvPath(scope.row.thumbUrl)" />
                    <template #reference>
                        <el-image style="width: 100%; height: 100%;" :src="$resolvPath(scope.row.thumbUrl)"
                            fit="cover" />
                    </template>
                </el-popover>
            </el-table-column>
            <el-form-item label="标题" prop="title">
                <el-input v-model.trim="form.title" placeholder="请输入标题" clearable />
            </el-form-item>
            <el-table-column label="显示" width="100" #default="scope">
                <span style="color: red;" v-if="scope.row.flag === 1">热销</span>
                <span style="color: green;" v-else-if="scope.row.flag === 2">新品</span>
                <span style="color: blue;" v-else-if="scope.row.flag === 3">精品</span>
                <span style="color: purple;" v-else-if="scope.row.flag === 4">清仓</span>
                <span style="color: orange;" v-else-if="scope.row.flag === 5">断码</span>
            </el-table-column>
            <el-table-column label="单价" width="100" prop="price" #default="scope">
                {{ '$' + scope.row.price.toFixed(2) }}
            </el-table-column>
            <el-table-column label="库存" width="100" prop="inventory" />
            <el-table-column label="状态" width="110" prop="status" #default="scope">
                <span style="color: red;" v-if="scope.row.status === 1">未审核</span>
                <span style="color: green;" v-else-if="scope.row.status === 2">已审核</span>
            </el-table-column>
            <el-table-column label="创建日期" prop="createTime" #default="scope">
                <span>{{ moment(scope.row.createTime).format('YYYY年MM月DD日') }}</span>
            </el-table-column>
            <el-table-column label="操作" width="150" #default="scope">
                <el-button plain type="primary" size="small" @click="openDialog(scope.row.id)">修改</el-button>
                <el-button plain type="danger" size="small" @click="delById(scope.row.id)">删除</el-button>
            </el-table-column>
        </el-table>


        <template #footer>
            <el-pagination :pager-count="5" background v-model:current-page="queryForm.pageNo"
                v-model:page-size="queryForm.pageSize" :page-sizes="[2, 3, 4, 5, 6, 7, 8, 9, 10]"
                layout="total, sizes, prev, pager, next, jumper" :total="totalRecord" @change="getProductList" />
        </template>
    </el-card>

    <Teleport to="body">

        <el-dialog v-model="dialogVisible" :title="`${$editId === 0 ? '新增' : '修改'}产品`" top="12vh" width="1000px">
            <el-form label-width="100px" :model="form" ref="formRef" :rules="rules">
                <el-form-item label="所属类别" prop="categoryId" width="150px">
                    <el-cascader style="width: 200px;" v-model="form.categoryId" :options="categoryOptionData"
                        :props="{ label: 'name', value: 'id' , emitPath:false}" />
                </el-form-item>
                <el-form-item label="摘要" prop="summary">
                    <el-input v-model.trim="form.summary" placeholder="请输入昵称" clearable />
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input v-model.trim="form.title" placeholder="请输入标题" clearable />
                </el-form-item>

                <el-form-item label="上传图片" prop="thumbUrl">
                    <el-tooltip effect="dark" content="请上传图片" placement="top">
                        <el-upload class="uploader" name="file" action="/api/manage/upload"
                            :headers="{ 'Authorrization': $authorization }" :show-file-list="false"
                            :on-success="(res: IApiResult) => onUploadSuccess(res, 'thumbUrl')"
                            style="width: 200px; height: 200px;">
                            <img v-if="form.thumbUrl" :src="$resolvPath(form.thumbUrl)">
                            <el-icon :size="20" color="#8c939d" v-else>
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-tooltip>
                </el-form-item>

                <el-form-item label="库存" prop="inventory">
                    <el-input-number style="width: 200px;" v-model.trim="form.inventory" placeholder="请输入库存"
                        clearable />
                </el-form-item>
                <el-form-item label="单价" prop="price">
                    <el-input-number style="width: 200px;" v-model.trim="form.price" placeholder="请输入单价">
                        <template #prefix>
                            <span>$</span>
                        </template>
                    </el-input-number>
                </el-form-item>

                <el-form-item label="显示类别">
                    <el-select style="width:200px" v-model.number="form.flag" placeholder="选择显示类型" clearable :value-on-clear="() => null">
                        <el-option label="热销" :value="1" />
                        <el-option label="新品" :value="2" />
                        <el-option label="精品" :value="3" />
                        <el-option label="清仓" :value="4" />
                        <el-option label="断码" :value="5" />
                    </el-select>
                </el-form-item>

                <el-form-item label="产品预览图">
                    <div class="preview-list">
                        <el-upload v-for="i in 5" :key="i" class="uploader" name="file" action="/api/manage/upload"
                            :on-success="(res: IApiResult) => onUploadSuccess(res, 'previewUrl' + i)"
                            :headers="{ 'Authorrization': $authorization }" :show-file-list="false"
                            style="width: 100px; height: 100px;">
                            <img v-if="form['previewUrl' + i as FormPreviewUrlKeys]"
                                :src="$resolvPath(form['previewUrl' + i as FormPreviewUrlKeys])">
                            <el-icon :size="20" color="#8c939d" v-else>
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <p style="line-height: 3;">请上传400x400像素的图片</p>
                    </div>
                </el-form-item>

                <el-form-item label="产品内容">
                    <MdEditor v-model="form.content"/>
                </el-form-item>
                <el-form-item label="规格包装">
                    <MdEditor v-model="form.specification"/>
                </el-form-item>
                <el-form-item label="售后保障">
                    <MdEditor v-model="form.aftermarket"/>
                </el-form-item>

                <el-form-item label="审核">
                    <el-switch v-model="form.status" :active-value="2" :inactive-value="1" />
                </el-form-item>
            </el-form>


            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrEditProuct()">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </Teleport>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import type { FormPreviewUrlKeys, IApiResult, IProduct } from '@/types';
import { productById, productEditOrAdd, productList, productDel, productBatchDel } from '@/apis/product';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { categoryList } from '@/apis/category';
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

const queryForm = reactive({
    status: '',
    keyword: '',
    minPrice: null,
    maxPrice: null,
    pageNo: 1,
    pageSize: 5,
})

const totalRecord = ref(0);
const loading = ref(false);
const tableData = ref<IProduct[]>([]);

const formRef = ref();
const $editId = ref(0);
const dialogVisible = ref(false);
const delIds = ref<number[]>([]);

const rules = reactive({
  categoryId: { required: true, message: '请选择所属类别' },
  title: { required: true, message: '请输入标题' },
  thumbUrl: { required: true, message: '请选上传图片' },
  inventory: { required: true, message: '请输入库存' },
  price: { required: true, message: '请输入单价' }
})


const getProductList = async () => {
    try {
        loading.value = true;
        const res = await productList(queryForm);
        if (res.data.code !== 0) {
            ElMessage.error(res.data.desc);
            return
        }
        tableData.value = res.data.data.records;
        totalRecord.value = res.data.data.total;
        loading.value = false;
    } catch (err) {
        ElMessage.error(JSON.stringify(err));
    }
}
getProductList();

const categoryOptionData = ref([]);
const getProductCategoryList = async () => {
    try {
        const res = await categoryList();
        if (res.data.code !== 0) {
            ElMessage.error('读取类别错误');
            return
        }
        categoryOptionData.value = res.data.data;
    } catch (err) {
        ElMessage.error(JSON.stringify(err));
    }
}
getProductCategoryList();



const queryFormRef = ref();
const onRefralsh = () => {
    queryFormRef.value?.resetFields();
    getProductList();
}

const form = reactive({
    id: 0,
    title: '',
    categoryId: 0,
    summary: '',
    thumbUrl: '',
    inventory: 0,
    price: 0,
    flag: 0,
    previewUrl1: '',
    previewUrl2: '',
    previewUrl3: '',
    previewUrl4: '',
    previewUrl5: '',
    content: '',
    specification: '',
    aftermarket: '',
    status: 2,
    categoryName: '',
})

const openDialog = async (editId: number = 0) => {
    $editId.value = editId;
    if (editId) {
        formRef.value?.clearValidate()
        try {
            console.log(editId);

            const res = await productById(editId);
            if (res.data.code !== 0) {
                ElMessage.error(res.data.desc);
                return
            }
            form.id = res.data.data.id;
            form.title = res.data.data.title;
            form.categoryId = res.data.data.categoryId;
            form.summary = res.data.data.summary;
            form.thumbUrl = res.data.data.thumbUrl;
            form.inventory = res.data.data.inventory;
            form.price = res.data.data.price;
            form.flag = res.data.data.flag;
            form.previewUrl1 = res.data.data.previewUrl1;
            form.previewUrl2 = res.data.data.previewUrl2;
            form.previewUrl3 = res.data.data.previewUrl3;
            form.previewUrl4 = res.data.data.previewUrl4;
            form.previewUrl5 = res.data.data.previewUrl5;
            form.status = res.data.data.status;
            form.content = res.data.data.content;
            form.specification = res.data.data.specification;
            form.aftermarket = res.data.data.aftermarket;
        } catch (err) {
            ElMessage.error(JSON.stringify(err));
        }

    } else {
        // 新增
        formRef.value?.resetFields();
        form.id = 0;
        form.title = '';
        form.categoryId = 0;
        form.summary = '';
        form.thumbUrl = '';
        form.inventory = 0;
        form.price = 0;
        form.flag = 0;
        form.previewUrl1 = '';
        form.previewUrl2 = '';
        form.previewUrl3 = '';
        form.previewUrl4 = '';
        form.previewUrl5 = '';
        form.status = 2;
        form.content = '';
        form.specification = '';
        form.aftermarket = '';
    }
    dialogVisible.value = true;
}

const onUploadSuccess = (res: IApiResult, field: string) => {
    if (res.code !== 0) {
        ElMessage.error(res.msg);
        return
    }
    form[field as FormPreviewUrlKeys] = res.data as string;
    ElMessage.success('上传成功');
}

const addOrEditProuct = async () => {
    try{
        const isValid = await formRef.value?.validate();
        if(!isValid)return;

        const res = await productEditOrAdd(form);
        if (res.data.code !== 0) {
            ElMessage.error(res.data.desc);
            return
        }
        ElMessage.success(form.id ? '修改成功' : '新增成功');

        dialogVisible.value = false;
        getProductList();
    } catch (err) {
        if(typeof err === 'string')ElMessage.error(err);
        console.log(err);
    }
}

const delById = async (id: number) => {
    try {
        const yes = await ElMessageBox.confirm('您确定要删除此条信息？', '提示', { type: 'warning' });
        if (!yes) return;
        const res = await productDel(id);
        if (res.data.code !== 0) {
            ElMessage.error(res.data.desc);
            return
        }
        ElMessage.success('删除成功');
        getProductList();
    } catch (err) {
        ElMessage.error(JSON.stringify(err))
    }
}

// 批量删除选中的轮播信息
const tableRef = ref();
const delBatchByIds = async () => {
    try {
        const yes = await ElMessageBox.confirm('您确定要删除所选信息？', '提示', { type: 'warning' });
        if (!yes) return;
        await productBatchDel(delIds.value);
        ElMessage.success('删除成功');
        getProductList();
    } catch (err) {
        if (err === 'cancel') {
            tableRef.value.clearSelection();
            return;
        }
    }
}

const onselectionChange = (val: IProduct[]) => {
    delIds.value = val.map((item: IProduct) => item.id) as number[]
}

</script>